package vip.liux.contracts.security.sms;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.Assert;

/**
 * 支持自定义前端手机号和验证码参数名的短信验证码登录过滤器
 */
public class SmsAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public static final String LOGIN_PAGE = "/login/sms";
    private String mobileParameter = "mobile";
    private String codeParameter = "code";

    public SmsAuthenticationFilter() {
        super();
        super.setPostOnly(true);
        super.setFilterProcessesUrl(LOGIN_PAGE);
    }

    public SmsAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
        super.setPostOnly(true);
        super.setFilterProcessesUrl(LOGIN_PAGE);
    }

    @Override
    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(this.mobileParameter);
    }

    @Override
    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(this.codeParameter);
    }

    public final String getMobileParameter() {
        return this.mobileParameter;
    }

    public void setMobileParameter(String mobileParameter) {
        Assert.hasText(mobileParameter, "mobile parameter must not be empty or null");
        this.mobileParameter = mobileParameter;
        super.setUsernameParameter(mobileParameter);
    }

    public final String getCodeParameter() {
        return this.codeParameter;
    }

    public void setCodeParameter(String codeParameter) {
        Assert.hasText(codeParameter, "code parameter must not be empty or null");
        this.codeParameter = codeParameter;
        super.setPasswordParameter(codeParameter);
    }
}